<?php

declare(strict_types=1);

namespace App\CustHub\Controller\Admin\Website;

use App\CustHub\Controller\BaseController;
use App\CustHub\Service\ChPotentialUserService;
use Hyperf\Di\Annotation\Inject;
use Hyperf\HttpServer\Annotation\Controller;
use Hyperf\HttpServer\Annotation\PostMapping;
use Mine\Exception\NormalStatusException;
use Psr\Container\ContainerExceptionInterface;
use Psr\Container\NotFoundExceptionInterface;
use Psr\Http\Message\ResponseInterface;

#[Controller(prefix: "custhub/chPotentialUser")]
class ChPotentialUserController extends BaseController
{
    #[Inject]
    protected ChPotentialUserService $service;

    /**
     * 添加手机号
     * @return ResponseInterface
     * @throws ContainerExceptionInterface
     * @throws NotFoundExceptionInterface
     */
    #[PostMapping('save')]
    public function save(): ResponseInterface
    {
        $mobile = $this->request->input('mobile');
        if (!preg_match('/^[0-9]{11}$/', $mobile)) {
            throw new NormalStatusException("请输入 11 位纯数字的手机号码");
        }

        $check = $this->service->mapper->model::query()->where('mobile', $mobile)->first();
        if ($check) {
            throw new NormalStatusException("请勿重复提交");
        }
        $data = $this->request->all();
        $data['created_at'] = date('Y-m-d H:i:s', time());
        $id = $this->service->save($data);
        if ($id == null)
        {
            throw new NormalStatusException("提交失败，请重新提交");
        }
        return $this->success('已提交，请等待客服联系',['id' => $id]);
    }
}